package com.wang.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.mall.bean.SysUser;
import com.wang.mall.bean.SysUserRole;
import com.wang.mall.mapper.SysUserMapper;
import com.wang.mall.service.SysRoleService;
import com.wang.mall.service.SysUserRoleService;
import com.wang.mall.service.SysUserService;
import com.wang.mall.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {


    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public PageUtils queryPage(Integer page, Integer size, String username) {
        // 只能查看自己创建的用户
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        IPage<SysUser> page1 = page(new Page<SysUser>(page, size),
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getCreateUserId, userId)
                        .like(!StringUtils.isEmpty(username), SysUser::getUsername, username));

        return new PageUtils(page1);
    }

    /**
     * 查询用户的所有菜单ID
     *
     * @param createUserId
     */
    @Override
    public List<Long> queryAllMenuId(Long createUserId) {
        return baseMapper.queryAllMenuId(createUserId);
    }

    @Override
    public void saveUser(SysUser user) {
        user.setCreateTime(new Date());
        //加密
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        this.save(user);

        //检查角色是否越权
        //checkRole(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());

    }

    @Override
    @Transactional
    public void update(SysUser user) {
        if (org.apache.commons.lang.StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        }
        this.updateById(user);


        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());

    }

    /**
     * 删除用户
     *
     * @param userIds
     */
    @Transactional
    @Override
    public void deleteBatch(Long[] userIds) {

        // 删除用户关联的角色
        boolean remove = sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userIds));
        // 删除用户
        this.removeByIds(Arrays.asList(userIds));
    }

    /**
     * 修改当前用户的密码
     *
     * @param newPassword
     * @param password
     * @param userId
     * @return
     */
    @Override
    public boolean updatePassword(String newPassword, String password, Long userId) {
        SysUser user = getById(userId);
        String oldPassword = user.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        // 比对旧密码
        if (!encoder.matches(password, oldPassword)) {
            return false;
        }

        // 设置新密码
        user.setPassword(encoder.encode(newPassword));
        boolean b = updateById(user);
        return b;
    }



}
